<style lang="scss">
.notice-rules .vview-select-tag {
  margin-top: 2px;
}
</style>

<template>
	<div class="notice-rules">
		<compWrapper theme="primary" title="基本信息">
			<compFormQuery
				:formdata="getBase"
				:labelWidth="120"
				:value="formData"
				class="margin-layout"
				v-if="type=='query'"
			></compFormQuery>
			<compFormEdit
				:formdata="getBase"
				:labelWidth="120"
				class="margin-layout"
				ref="formbase"
				v-else
				v-model="formData"
			/>
		</compWrapper>
        <div class="text-right">
            <Button @click="submit" class="margin-right-10" type="primary" v-if="type!=='query'">确认</Button>
            <Button @click="close">返回</Button>
        </div>
		<!-- 弹框 -->
		<compModal @on-close="operate.show=false" v-bind="operate" v-model="operate.show">
			<component
				:is="operate.component"
				@on-close="operate.show=false"
				v-bind="operate.props"
				v-if="operate.component"
				v-on="operate.on"
			/>
		</compModal>
		<Spin size="large" fix v-if="loading"></Spin>
	</div>
</template>

<script>
import { resolveComponent } from 'vue';
import { mapGetters } from 'vuex'
import mixin from '../mixin'
import compTemplate from './template'
import compUserlist from './userlist'
import { HttpRule, HttpSaveRule, HttpTemplate } from '../../../service/notice'

export default {
    mixins: [mixin],
    components: {
        compTemplate,
        compUserlist
    },
    data () {
        return {
        loading: false,
        type: this.$route.params.type,
        id: this.$route.query.id,
        dingtalkbotTipsText: `
                <div>
                    <p>钉钉群机器人添加方法：</p>
                    <p>
                    打开钉钉群组 → 聊天设置 → 智能群助手 → 添加机器人 → 添加机器人 → 自定义 → 添加
                    </p>
                    <p>机器人名字: 【填写】<strong>根据需求自行填写，比如：【销售渠道群商舟通知服务】</strong></p>
                    <p>安全设置: → 【√勾选】<strong>IP地址 (段)</strong></p>
                    <p>输入多条四海商舟服务器ip地址，（点击添加按钮添加多条ip地址）</p>
                    <ol>
                        <li>47.98.136.25</li>
                        <li>47.96.19.169</li>
                        <li>47.91.155.201</li>
                        <li>221.226.84.173</li>
                    </ol>
                    <p>勾选 【√我已阅读并同意《自定义机器人服务及免责条款》】</p>
                    <p>点击【完成】</p>
                    <p>点击【复制】得到机器人的完整webhook地址（地址最后=等号后续部分为平台填写所需token值）</p>
                    <p>添加后如需重新查看webhook：打开钉钉群组 → 聊天设置 → 智能群助手 → 【上述填写的机器人名字】 → webhook地址 → 【复制】 </p>
                    <p>平台填写仅机器人Token仅保留webhook最后的token部分不粘贴完整链接地址：</p>
                    <p>比如：</p>
                    <p><code>
                        https://oapi.dingtalk.com/robot/send?access_token=0d743c0f5d62269f74bee08d8611a52877f0b868d6ee2370b7f269479adce9de
                    </code> </p>
                    <p>只保留</p>
                    <p><code>0d743c0f5d62269f74bee08d8611a52877f0b868d6ee2370b7f269479adce9de</code></p>
                </div>
                `,
        formData: {
            'priority': 0,
            'langKey': '',
            'matchOrgIds': '',
            'matchAccountIds': [],
            'matchLineIds': [],
            'matchOrgwarehouseIds': [],
            'isGlobal': '0',
            'sendChannels': ['inbox'],
            'allCreator':['toSourceCreator',],
            'toSourceCreator': 1,  // 是否发送给源事件创建者 (单据创建者)
            'toProjectAgent': 2,   // 是否发送给项目负责人
            'toAccountAgent': 2, // 是否发送给渠道账号负责人
            'toOrgwarehouseAgent': 2, // 是否发送给组织仓库负责人
            'toOrganizationAgent': 2, // 是否发送给组织负责人
            'toServiceAgent': 2, // 是否发送给服务商负责人
            'relExtra': '',
            'recipientsSetup': {
            'userData': {},
            'groupData': {},
            },
            'tplTitle': '',
            'userNames': [],
            'ruleType': 1,
            active:1,
        },
        operate: {
            show: false,
        },
        usersData: []
        }
    },
    created () {
        this.getDetial()
    },
    computed: {
        ...mapGetters(['isSuper']),
        ...mapGetters('dictionary', ['getProductList', 'getAccountList', 'getWarehouseList', 'getOrgList']),
        getBase () {
        const isManageRuleType = this.formData.ruleType == 2
        const isGlobalType = this.formData.isGlobal == 1
        // console.log(isGlobalType,this.formData.isGlobal,'isGlobalTypeisGlobalTypeisGlobalType')
        return [
            {
                label: '规则名称',
                key: 'title',
                tag: 'Input',
            },
            {
                label: '状态',
                key: 'active',
                tag: 'Select',
                options: this.getRuleStatus,
                props: {
                    strict: true,
                },
            },
            {
                label: '是否全局',
                key: 'isGlobal',
                tag:'Radio',
                show: this.isSuper,
                options: [{
                    value: '1',
                    label: '是'
                }, {
                    value: '0',
                    label: '否'
                }],
            },
            {
                label: '提醒规则类型',
                key: 'ruleType',
                show: this.isSuper && !isGlobalType,
                tag: 'Select',
                options: this.getRuleTypes,
                props: {
                    strict: true,
                },
            },
            {
                label: '通知模板',
                key: 'tplTitle',
                tag: "div",
                required: true,
                children: (h) => {
                    return h(resolveComponent("Input"),{
                        modelValue:this.formData.tplTitle
                    },{
                        suffix: () => {
                            return h(resolveComponent("Icon"), {
                                type: "ios-search",
                                onClick: () => {
                                    this.handleTemplateModal()
                                }
                            },)
                        }
                    });
                },
                // props: {
                //     readonly: true
                // }
            },
            {
                label: '通知方式',
                key: 'sendChannels',
                tag: 'Select',
                options: this.getSendChannels,
                props: {
                    multiple: true,
                },
                render:()=>{
                    let label = [];
                    this.formData.sendChannels.forEach(labelItem => {
                        this.getSendChannels.map(item => {
                            if (item.value == labelItem) label.push(item.label+',');
                        })
                    });
                    return label
                }
            },
            {
                label: '所属组织',
                key: 'matchOrgIds',
                tag: 'Select',
                show: !isGlobalType && isManageRuleType,
                options: this.getOrgList,
                props: {
                    filterable: true,
                    multiple: true,
                },
                required: false,
            },
            {
                label: '项目',
                key: 'matchLineIds',
                tag: 'Select',
                show: !isGlobalType && !isManageRuleType,
                options: this.getProductList,
                props: {
                    filterable: true,
                    multiple: true,
                },
                required: false,
                render:()=>{
                    let label = [];
                    this.formData.matchLineIds.forEach(labelItem => {
                        this.getProductList.map(item => {
                            if (item.value == labelItem) label.push(item.label+',');
                        })
                    });
                    return label
                }
            },
            {
                label: '渠道',
                key: 'matchAccountIds',
                tag: 'Select',
                show: !isGlobalType && !isManageRuleType,
                options: this.getAccountList,
                props: {
                    // filterable: true,
                    multiple: true,
                },
                required: false,
                render:()=>{
                    let label = [];
                    this.formData.matchAccountIds.forEach(labelItem => {
                        this.getAccountList.map(item => {
                            if (item.value == labelItem) label.push(item.label+',');
                        })
                    });
                    return label
                }
            },
            {
                label: '仓库',
                tag: 'Select',
                key: 'matchOrgwarehouseIds',
                show: !isGlobalType && !isManageRuleType,
                options: this.getWarehouseList,
                props: {
                    filterable: true,
                    multiple: true,
                },
                required: false,
                render:()=>{
                    let label = [];
                    this.formData.matchOrgwarehouseIds.forEach(labelItem => {
                        this.getWarehouseList.map(item => {
                            if (item.value == labelItem) label.push(item.label+',');
                        })
                    });
                    return label
                }
            },
            {
                label: '通知人',
                key: 'allCreator',
                // options: this.getNotifierList,
                tag:'CheckboxGroup',
                children: (h) => {
                    let _this = this;
                    return h(("span"),{
                        modelValue:this.formData.allCreator,
                    },{
                        default:() => [
                        _this.getNotifierList.map(json=>{
                            return h(resolveComponent("Checkbox"),
                            {
                                label: json.key,
                            },json.label);
                        })
                        ]
                    }
                    );
                },
                on:{
                    'on-change':(val)=>{
                        if(this.formData.allCreator.indexOf('toCustomeCreator')>0){
                            this.formData.toCustomeCreator = 1
                        }else{
                            this.formData.toCustomeCreator = 0
                        }

                    }
                },
                render:()=>{
                    let label = [];
                    this.formData.allCreator.forEach(labelItem => {
                        this.getNotifierList.map(item => {
                            if (item.key == labelItem) label.push(item.label+',');
                        })
                    });
                    return label
                }
            },
            {
                label: '指定人员',
                key: 'userNames',
                tag:'div',
                show: this.formData.toCustomeCreator == 1,
                children: () => {
                    let _this = this;
                    return h(resolveComponent("Input"),{
                        modelValue:this.formData.userNames
                    },{
                        suffix: () => {
                            return h(resolveComponent("Icon"), {
                                type: "ios-search",
                                onClick: () => {
                                    _this.handleUserModal()
                                }
                            },)
                        }
                    });
                },
                on: {
                    'on-remove-item': (value, index) => {
                    this.usersData.splice(index, 1)
                    this.updateUserNames()
                    },
                    'on-clear': (value, index) => {
                    this.usersData = []
                    this.formData.userNames = []
                    }
                },
                props: {
                    multiple: true,
                    clear: true,
                    readonly: true
                },
            },
            {
                label: '钉钉群机器人',
                key: 'groupTokens',
                // tag: 'Input',
                // props: {
                //     multiple: true,
                // },
                tag: 'Input',
                props: {
                    type: 'textarea',
                    rows: 2,
                    placeholder:'支持输入多个，一行一个token'
                },
                show: this.formData.sendChannels.indexOf('dingtalkbot') > -1,
                popper:this.type=='query'?'':'如果通知方式是钉钉，此栏位必填。请填写钉钉群组的Token。',
                on: {
                    'on-blur': this.trimWebhookPrefix
                },
                
            },
            {
                label: '机器人填写说明',
                valueText: this.dingtalkbotTipsText,
                show: this.formData.sendChannels.indexOf('dingtalkbot') > -1,
                query: true,
            },
            {
                label: '描述',
                key: 'remark',
                tag: 'Input',
                props: {
                    type: 'textarea',
                    rows: 2,
                },
                required: false,
            },
        ]
        }
    },
    methods: {
        trimWebhookPrefix (stringval) {
            let INid = stringval.replace(/\n/g, ",");
            let webhookUrls = INid.split(",");
            console.log(webhookUrls)
            if (webhookUrls.length > 0) {
                let groupTokens = webhookUrls.map((item) => {
                if (item && item.indexOf('=') !== -1 && (item.indexOf('=') != item.length - 1)) {
                    return item.substring(item.indexOf('=') + 1)
                } else {
                    return item
                }
                })
                // console.log(groupTokens)
                // console.log(Array.from(new Set(groupTokens)))
                this.formData.groupTokens = Array.from(new Set(groupTokens))
            }
        },
        updateUserNames () {
            this.formData.userNames = this.usersData.map((item) => item.relReceiverName)
            // 重新渲染checkout的内容，现在用的统一组件，需要进行重新渲染操作
            this.formData.allCreator = [];
            Object.keys(this.getNotifierList).map((key,val) => {
                if(this.formData[this.getNotifierList[key].key] == 1 || this.formData[this.getNotifierList[key].key] == true){
                    this.formData.allCreator.push(this.getNotifierList[key].key)
                }
            });
            this.formData.toCustomeCreator = this.formData.toCustomeCreator || !!this.formData.userNames.length
            if(this.formData.toCustomeCreator){
                this.formData.allCreator.push('toCustomeCreator')
            }


        },
        close () {
            this.$router.push({
                name: 'noticeRules'
            })
        },
        handleTemplateModal () {
            this.operate = {
                title: '选择模板',
                show: true,
                width: 'large',
                component: 'compTemplate',
                on: {
                //处理关联模板
                'on-data': (data) => {
                    this.operate = {}
                    this.formData = {
                    ...this.formData,
                    tplId: data.id,
                    tplTitle: data.title,
                    bizeventTypeId: data.bizeventTypeId
                    }
                }
                },
                showFooter: false,
            }
        },
        handleUserModal () {
            this.operate = {
                title: '用户',
                show: true,
                width: 'large',
                component: 'compUserlist',
                props: {
                initFormData: {
                    'ids': this.usersData.map((item) => item.relReceiverId).join(',')
                }
                },
                on: {
                'on-data': (row) => {
                    
                    this.operate = {}
                    const isExist = this.usersData.some((item) => item.relReceiverId == row.id)
                    if (!isExist) {
                    this.usersData.push({
                        'relReceiverId': row.id, // 接受者id号（群组id）
                        'relReceiverLabel': row.code, // 接受者唯一标识（群组code）
                        'relReceiverLabelAlt': row.email, // 接受者唯一标识（钉钉群token）
                        'relReceiverName': row.name, // 接受者名称
                    })
                    this.updateUserNames()
                    }
                }
                },
                showFooter: false,
            }
        },
        //处理群数据
        handleGroupData (tokens) {
            const groupData = this.formData.recipientsSetup.groupData
            const result = {};
            (tokens || []).forEach((token) => {
                result[`dingtalkbot${token}`] = {
                '4': {
                    'relReasonType': 1,    //     原因类型
                    'relChannelType': 4, // 下发通道类型
                    'relReceiverType': 0, // 接受者类型
                    'relReceiverId': 0, // 接受者id号（群组id）
                    'relReceiverLabel': token, // 接受者唯一标识（群组code）
                    'relReceiverLabelAlt': token, // 接受者唯一标识（钉钉群token）
                    'relReceiverName': token, // 接受者名称
                    'relReceiverExtra': '', // 关联扩展信息
                    ...(groupData[`dingtalkbot${token}`] || {})
                }
                }
            })
            this.formData.recipientsSetup.groupData = result
        },
        //处理指定人数据
        handleUserData () {
            const userData = this.formData.recipientsSetup.userData
            const result = {}
            this.usersData.forEach((item) => {
                result[item.relReceiverId] = {
                0: {
                    'relReasonType': 1,    //     原因类型
                    'relChannelType': 4, // 下发通道类型
                    'relReceiverType': 0, // 接受者类型
                    // "relReceiverId": item.id, // 接受者id号（群组id）
                    // "relReceiverLabel": item.code, // 接受者唯一标识（群组code）
                    // "relReceiverLabelAlt": item.email, // 接受者唯一标识（钉钉群token）
                    // "relReceiverName": item.name, // 接受者名称
                    'relReceiverExtra': '',// 关联扩展信息,
                    ...item,
                    ...(userData[item.relReceiverId] || {})
                }
                }
            })
            this.formData.recipientsSetup.userData = result
        },
        handleResponse (data) {
            const entity = data.entity || {}
            const recipientsSetup = JSON.parse(entity.recipientsSetup || '{}')
            //转化response ids
            const handleResIds = (name) => {
                const names = name + 's'
                return entity[names] ? entity[names].split(',') : (entity[name] == 0 ? [] : [entity[name]])
            }
            Object.values(recipientsSetup.userData || {}).forEach(item => {
                const data = item[0]
                if (data) this.usersData.push(data)
            })
            this.formData = {
                ...entity,
                recipientsSetup,
                isGlobal: data.isGlobal ? '1' : '0',
                sendChannels: (entity.sendChannels || '').split(','),
                matchAccountIds: handleResIds('matchAccountId'),
                matchLineIds: handleResIds('matchLineId'),
                matchOrgwarehouseIds: handleResIds('matchOrgwarehouseId'),
                matchOrgIds: handleResIds('matchOrgId'),
                groupTokens: Object.keys(recipientsSetup.groupData || {}).map(str => str.slice(11)),
            }
            this.formData.matchLineIds = this.formData.matchLineIds.map(item => {
                return parseInt(item);
            });
            this.formData.matchAccountIds = this.formData.matchAccountIds.map(item => {
                return parseInt(item);
            });
            this.formData.matchOrgwarehouseIds = this.formData.matchOrgwarehouseIds.map(item => {
                return parseInt(item);
            });
            // console.log(this.formData.isGlobal,'isGlobalisGlobalisGlobal')
            this.updateUserNames()
            this.getTemplateData()
        },
        //获取详情
        async getDetial () {
            if (this.type === 'add') return
            this.loading = true
            await HttpRule({ id: this.id }).then(res => {
                this.handleResponse(res.data || {})
                this.loading = false
            }).catch(err => {
                this.$Message.error(err.message)
                this.loading = false
            })
        },
        //保存数据
        async submit () {
            const valid = await this.$refs.formbase.validate()
            if (!valid) return
            this.loading = true
            await this.handleUserData()
            await this.handleGroupData(this.formData.groupTokens || [])
            //转化ids
            const handleIds = (name) => {
                const names = name + 's'
                const ids = this.formData[names] || []
                return ids.length > 1 ? {
                [name]: 0,
                [names]: ids.join(','),
                } : {
                [name]: ids[0] || 0,
                [names]: '',
                }
            }

            // 渲染checkbox的传输修改
            this.formData.allCreator.map(item=>{
                this.formData[item] = 1
            })
            // console.log(this.formData,'this.formDatathis.formDatathis.formDatathis.formDatathis.formData')
            // return

            const formData = {
                ...this.formData,
                ...handleIds('matchAccountId'),
                ...handleIds('matchLineId'),
                ...handleIds('matchOrgwarehouseId'),
                ...handleIds('matchOrgId'),
                recipientsSetup: JSON.stringify(this.formData.recipientsSetup)
            }
            if (this.formData.isGlobal == 1) {
                formData.matchOrgId = 0
                formData.matchOrgIds = ''
            }
            if (this.formData.ruleType == 1 && this.formData.isGlobal == 0) {
                formData.matchOrgId = global.SYSID
                formData.matchOrgIds = ''
            }
            if (this.formData.ruleType == 2) {
                formData.matchAccountId = 0
                formData.matchAccountIds = ''
                formData.matchLineId = 0
                formData.matchLineIds = ''
                formData.matchOrgwarehouseId = 0
                formData.matchOrgwarehouseIds = ''
            }



            await HttpSaveRule(formData).then(res=>{
                this.$Message.success(res.message);
                this.close()
            }).catch(err => {
                this.loading = false
                this.$Message.error({
                    content: err.message,
                    duration: 30,
                    closable: true
                });
            })
        },
            
            //Template数据
        async getTemplateData () {
            await HttpTemplate({ id: this.formData.tplId }).then(res => {
                this.formData = { ...this.formData, tplTitle: res.data.entity.title }
            })
        },
    }
}
</script>
